package com.gingko.duominuo.data.source.repository

import com.gingko.duominuo.data.ApiResponse
import com.gingko.duominuo.data.TaskConfigVo
import com.gingko.duominuo.data.datastore.DataStoreHelper
import com.gingko.duominuo.data.isSuccess
import com.gingko.duominuo.data.model.*
import com.gingko.duominuo.data.request.*
import com.gingko.duominuo.data.source.local.dao.DownloadDao
import com.gingko.duominuo.data.source.local.dao.JobWorkDao
import com.gingko.duominuo.data.source.local.dao.NameMappingDao
import com.gingko.duominuo.data.source.local.dao.UserDao
import com.gingko.duominuo.network.api.GinkgoService
import com.gingko.duominuo.network.download.OSSUpload
import com.gingko.duominuo.utils.NameMappingUtils
import com.gingkor.common.ext.toMap
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import okhttp3.ResponseBody
import retrofit2.Response
import javax.inject.Inject

class GinkgoRepository @Inject constructor(
    private val ginkgoService: GinkgoService,
    private val userDao: UserDao,
    private val jobWorkDao: JobWorkDao,
    private val nameMappingDao: NameMappingDao,
    private val downloadDao: DownloadDao
) {

    suspend fun sendSMSCode(phoneNumber: String): ApiResponse<String> {
        return ginkgoService.sendVerifyCode(SendSMSReqVo(phoneNumber))
    }

    suspend fun login(loginReqVo: LoginReqVo): ApiResponse<UserVo> {
        val result = ginkgoService.login(loginReqVo.toMap())
        withContext(Dispatchers.IO) {
            if (result.isSuccess() && result.data?.status == 1) {
                DataStoreHelper.saveIsLogin(true)
                result.data.account?.let { DataStoreHelper.saveUserId(it) }
                userDao.insertUser(result.data)
            }
        }
        return result
    }


    suspend fun register(registerReqVo: RegisterReqVo): ApiResponse<String> {
        return ginkgoService.register(registerReqVo)
    }

    suspend fun getTasks(taskReqVo: TaskReqVo): ApiResponse<List<TaskVo>> {
        return ginkgoService.getTasks(taskReqVo.toMap())
    }

    suspend fun createTaskOrder(createTaskReqVo: CreateTaskReqVo): ApiResponse<CreateTaskVo> {
        return ginkgoService.createTask(createTaskReqVo)
    }


    suspend fun getWorkOrder(orderReqVo: OrderReqVo): ApiResponse<WorkOrderListVo> {
        return ginkgoService.getWorkOrders(orderReqVo.toMap())
    }

    suspend fun submitWorkOrder(submitWorkOrderReqVo: SubmitWorkOrderReqVo): ApiResponse<String> {
        return ginkgoService.submitWorkOrder(submitWorkOrderReqVo)
    }

    suspend fun getWorkOrderDetail(orderDetailReqVo: OrderDetailReqVo): ApiResponse<WorkOrderDetailVo> {
        return ginkgoService.getWorkOrderDetail(orderDetailReqVo)
    }

    suspend fun getJobReviewContent(jobId: String): ApiResponse<JobReviewContentVo> {
        return ginkgoService.getJobReviewContent(jobId)
    }

    suspend fun queryUpgradeInfoByUrl(url: String): DownloadInfo? {
        return downloadDao.queryByUrl(url)
    }

    suspend fun insertOrReplaceUpgradeInfo(downloadInfo: DownloadInfo) {
        downloadDao.insertOrReplace(downloadInfo)
    }

    suspend fun insertJobWork(jobWorkVo: JobWorkVo): List<Long> {
        return jobWorkDao.insertTaskWork(jobWorkVo)
    }

    suspend fun queryJobWork(workId: String): List<JobWorkVo>? {
        return jobWorkDao.queryTask(DataStoreHelper.getUserId()!!, workId)
    }

    suspend fun queryJobWork(workId: String, jobId: String): JobWorkVo? {
        return jobWorkDao.queryTaskWork(DataStoreHelper.getUserId()!!, workId, jobId)
    }

    suspend fun deleteAllJobWork() {
        jobWorkDao.deleteAll()
    }

    suspend fun deleteUpgradeInfo(downloadInfo: DownloadInfo) {
        downloadDao.delete(downloadInfo)
    }

    suspend fun download(startPosition: Long, url: String): Response<ResponseBody> {
        return Response.success(null)
    }

    suspend fun getUserInfoFromDb(): UserVo? {
        return userDao.queryUser(DataStoreHelper.getUserId()!!)
    }

    suspend fun getTaskFilter(): TaskFilterVo {
        val result = ginkgoService.getTaskFilter(OSSUpload.RESOURCE_DATA_END_POINT + "/filter.json")
        nameMappingDao.deleteAll()
        result.forEach { group ->
            group.values?.forEach {
                val nameMapping = NameMappingVo(group = group.name, name = it.name, desc = it.desc)
                nameMappingDao.insertNameMapping(nameMapping)
            }
        }
        NameMappingUtils.initData()
        return result
    }

    suspend fun getInterceptAndInject(url: String): List<InjectAndInterceptVo> {
        return ginkgoService.getJsInject(url)
    }


    suspend fun getTaskConfig(): TaskConfigVo {
        return ginkgoService.getTaskConfig(OSSUpload.RESOURCE_DATA_END_POINT + "/conf.json")
    }
}